class ChangePasswordPage < Page

  attr_reader :current_website_user

  def process(request, response)
    @current_website_user = WebsiteUser.find(request.session[:website_user_id])
    
    if @current_website_user.nil?
      response.redirect "/"+Page.find_by_class_name("LoginPage").slug
      return
    end
    
    if request.post?
      @current_website_user.attributes = request.parameters[:website_user]
      if @current_website_user.save
        @success = true
      else
        @error = true
      end
    end
    
    super(request, response)
  end
  
  def cache?
    false
  end
  
  tag "login" do |tag|
    tag.expand
  end
  
  tag "login:change" do |tag|
    tag.expand
  end

  desc %{Form to change the website user details}
  tag "login:change:form" do |tag|
    results =  %Q(<form action="#{url}" method="post" #{add_attrs_to_tag(tag)} >)
    results << tag.expand
    results << %Q(</form>)
  end

  desc %{Password field}
  tag "login:change:password" do |tag|
    %Q(<input type="password" name="website_user[password]" id="website_user_password" #{add_attrs_to_tag(tag)} />)
  end

  desc %{Password confirmation field}
  tag "login:change:password_confirmation" do |tag|
    %Q(<input type="password" name="website_user[password_confirmation]" id="website_user_password_confirmation" #{add_attrs_to_tag(tag)} />)
  end
  
  desc %{Nickname field}
  tag "login:change:nickname" do |tag|
    %Q(<input type="text" name="website_user[nickname]" id="website_user_nickname" value="#{tag.locals.page.current_website_user.nickname}" #{add_attrs_to_tag(tag)} />)
  end
  
  desc %{Submit button}
  tag "login:change:submit" do |tag|
    %Q(<input type="submit" #{add_attrs_to_tag(tag)} />)
  end
  
  desc %{Error tag}
  tag "login:change:if_error" do |tag|
    tag.expand if @error
  end
  
  desc %{Success tag}
  tag "login:change:if_success" do |tag|
    tag.expand if @success
  end


  protected
  
  def add_attrs_to_tag(tag)
    results = ""
    tag.attr.each do |attr, value|
      results << "#{attr}=#{value} "
    end
    results
  end
end